<?php

namespace app\admin\model;

use think\Model;
use think\Db;

class UserOptions extends Model
{
    // 表名
    protected $name = 'user_options';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = false;

    // 定义时间戳字段名
    protected $createTime = false;
    protected $updateTime = false;

    // 追加属性
    protected $append = [
        'create_time_text',
        'options_text'
    ];






    public function getCreateTimeTextAttr($value, $data)
    {
        $value = $value ? $value : $data['create_time'];
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    public function getOptionsTextAttr($value, $data)
    {
        $options = json_decode($data['options']);
        $str = '';
        if($options) {
            foreach ($options as $k => $v) {
                if($k !== 0) {
                    $pre = '<br>';
                }else{
                    $pre = '';
                }
                $str .=  $pre . '问题：' . Db::name('question')->where(['id' => $k])->value('title') . '<br/>' . '选项：';
                foreach ($v as $vv) {
                    $str .= Db::name('options')->where(['id' => $vv])->value('title');
                }
            }
        }
        return $str;
    }

    protected function setCreateTimeAttr($value)
    {
        return $value && !is_numeric($value) ? strtotime($value) : $value;
    }


    public function user()
    {
        return $this->belongsTo('User', 'user_id')->setEagerlyType(0);
    }


}
